package com.yyq.sos.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.yyq.sos.constants.Constants;
import com.yyq.sos.pojo.SysSequences;

@Repository("sysSequencesDao")
public class SysSequencesDaoImpl extends BaseDaoImpl implements  SysSequencesDao
{
	/**
	 * 取得下一个主键序列值,表结构：table_name,next_value,step_value
	 * @param tableName
	 * @return
	 * @throws SQLException 
	 * @throws Exception
	 */
	

	public SysSequences getSeqs(String tableName){
		SysSequences obj = new SysSequences();
		Session session = null;
		Connection conn = null;
		try{
			session = this.getSessionFactory().openSession();
			conn = session.connection();
			conn.setAutoCommit(false);
			Statement st = conn.createStatement();
			int i = st.executeUpdate("update ss_sys_sequences set curr_value=curr_value+incrementvalue where table_name='"+tableName+"'");
			st.close();
			st = conn.createStatement();
			if(i!=0){
				ResultSet rs = st.executeQuery("select curr_value,incrementvalue from ss_sys_sequences where  table_name='"+tableName+"'");
				while(rs.next()){
					obj.setTableName(tableName);
					obj.setCurrValue(new Long(rs.getLong(1)-rs.getLong(2)));
					obj.setIncrementValue(new Long(rs.getLong(2)));
				}
				rs.close();
				st.close();
				System.out.println("--------------");
			}else{
				long currValue = Constants.DEFAULT_CURR_VALUE+Constants.DEFAULT_INCREMENT_VALUE;
				String sql = "insert into ss_sys_sequences values ('"+tableName+"','',"+currValue
					+",1,"+Constants.DEFAULT_INCREMENT_VALUE+","+Constants.DEFAULT_CURR_VALUE+","+Integer.MAX_VALUE+")";
				System.out.println(sql);
				st.executeUpdate(sql);
				obj.setTableName(tableName);
				obj.setCurrValue(new Long(Constants.DEFAULT_CURR_VALUE));
				obj.setIncrementValue(new Long(Constants.DEFAULT_INCREMENT_VALUE));
				st.close();
				System.out.println("=================");
			}
			conn.commit();
			conn.setAutoCommit(true);
		}catch(Exception e){
			
		}finally{
			try {
				conn.close();
				if(session!=null && (session.isOpen() || session.isConnected()))
					session.close();
			} catch (SQLException e) {}
		}
		return obj;
	}
}
